package com.wsc.wsckeeper.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import android.os.Environment;

public class FileUtils {

	public static File mkDirStructure(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file;
	}

	public static File mkSDCardDirStructure(String path) {
		return mkDirStructure(Environment.getExternalStorageDirectory() + "/" + path);
	}

	public static void copyFile(File src, File dst) throws IOException {
		FileInputStream in = new FileInputStream(src);
		FileOutputStream out = new FileOutputStream(dst);
		FileChannel fromChannel = null, toChannel = null;
		try {
			fromChannel = in.getChannel();
			toChannel = out.getChannel();
			fromChannel.transferTo(0, fromChannel.size(), toChannel);
		} finally {
			if (fromChannel != null)
				fromChannel.close();
			if (toChannel != null)
				toChannel.close();
			if (in != null)
				in.close();
			if (out != null)
				out.close();
		}
	}

	public static void rmDirStructure(String path) throws IOException {
		File rootPath = new File(path);
		if (rootPath.exists()) {
			delete(rootPath);
		}
	}

	public static boolean delete(File file) throws IOException {
		boolean result = false;
		if (file.isDirectory()) {
			// directory is empty, then delete it
			if (file.list().length == 0) {
				result = file.delete();
			} else {

				// list all the directory contents
				String files[] = file.list();

				for (String temp : files) {
					// construct the file structure
					File fileDelete = new File(file, temp);
					// recursive delete
					delete(fileDelete);
				}

				// check the directory again, if empty then delete it
				if (file.list().length == 0) {
					result = file.delete();
				}
			}

		} else {
			// if file, then delete it
			result = file.delete();
		}
		return result;
	}
}
